//数据库查询
var http = require("http")
var redisDao = require("./redisDao")
var utils = require("./utils.js")
const querystring = require("querystring")
const chatGPT = require("./chatGPT/chatGPT.js")
const mysqlDao = require("./mysqlDao.js")
const url = require('url');
const oneDayTime = 86400000
var model = function() {
	var self = this
	var posts = {}
	var gets = {}
	var local = {}
	this.init = function (server) {
		self.server = server
		for(var key in posts){
			server.post(key,posts[key])
		}
		for(var key in gets){
			server.get(key,gets[key])
		}
	}
	//获取系统数据
	posts["/getOSData"] = function(req,res) {
		var data = req.body
		local.post(data.ip,3001,"/getOSData",{},function(data) {
			res.send(data)
		})
	}
	//版本数据
	posts["/total_info"] = function(req,res) {
		var infos = self.server.edition.getEditions()
		var str = (new Date()).toLocaleDateString()
		var list = []
		var multiList = []
		var statementList = []
		for(var i in infos){
			list.push({name : i,data : infos[i]})
			multiList.push(["hgetall","editionTotal:"+i])
			statementList.push(["hgetall","statementTotal:"+i])
		}
		redisDao.multi(multiList,function(err,data) {
			for(var i = 0;i < data.length;i++)
				list[i]["info"] = data[i]
			redisDao.multi(statementList,function(err,sdata) {
				for(var i = 0;i < sdata.length;i++)
					list[i]["statement"] = sdata[i]
				res.send(list)
			})
		})
	}
	//今日收益
	posts["/day_info"] = function(req,res) {
		var infos = self.server.edition.getEditions()
		var str = (new Date()).toLocaleDateString()
		var list = []
		var multiList = []
		for(var i in infos){
			list.push(infos[i])
			multiList.push(["hget","editionDay:"+i,str])
		}
		redisDao.multi(multiList,function(err,data) {
			for(var i = 0;i < data.length;i++)
				list[i]["info"] = data[i]
			res.send(list)
		})
	}
	//往日收益
	posts["/history_info"] = function(req,res) {
		var data = req.body
		var time = data.time
		var num = data.num
		var infos = self.server.edition.getEditions()
		var list = []
		var multiList = []
		var strs = []
		var date = new Date(time)
		for(var j = 0;j <= num;j++){
			strs[j] = (new Date(date.getTime()-oneDayTime*j)).toLocaleDateString()
		}
		for(var i in infos){
			list.push(infos[i])
			for(var j = 0;j <= num;j++)
				multiList.push(["hget","editionDay:"+i,strs[j]])
		}
		redisDao.multi(multiList,function(err,data) {
			for(var i = 0;i < list.length;i++){
				var info = []
				for(var j = 0;j <= num;j++){
					if(!data[0]){
						data[0] = JSON.stringify({date:strs[j]})
					}
					info.push(data.shift())
				}
				list[i]["list"] = info
			}
			res.send(list)
		})
	}
	//往周收益
	posts["/history_week"] = function(req,res) {
		var infos = self.server.edition.getEditions()
		var list = []
		var multiList = []
		var strs = []
		for(var j = 5;j >= 0;j--){
			strs[j] = utils.getBeforeWeek(j)
		}
		for(var i in infos){
			list.push(infos[i])
			for(var j = 0;j < 6;j++)
				multiList.push(["hget","editionWeek:"+i,strs[j]])
		}
		redisDao.multi(multiList,function(err,data) {
			for(var i = 0;i < list.length;i++){
				var info = []
				for(var j = 0;j < 6;j++){
					if(!data[0]){
						data[0] = JSON.stringify({date:strs[j]})
					}
					info.push(data.shift())
				}
				list[i]["list"] = info
			}
			res.send(list)
		})
	}
	//往月收益
	posts["/history_month"] = function(req,res) {
		var data = req.body
		var time = data.time
		var num = data.num
		var infos = self.server.edition.getEditions()
		var list = []
		var multiList = []
		var strs = []
		for(var j = 0;j <= num;j++){
			strs[j] = utils.getBeforeMonth(j,time)
		}
		for(var i in infos){
			list.push(infos[i])
			for(var j = 0;j <= num;j++)
				multiList.push(["hget","editionMonth:"+i,strs[j]])
		}
		redisDao.multi(multiList,function(err,data) {
			for(var i = 0;i < list.length;i++){
				var info = []
				for(var j = 0;j <= num;j++){
					if(!data[0]){
						data[0] = JSON.stringify({date:strs[j]})
					}
					info.push(data.shift())
				}
				list[i]["list"] = info
			}
			res.send(list)
		})
	}
	//版本往月收益
	posts["/id_month"] = function(req,res) {
		var data = req.body
		var time = data.time
		var num = data.num
		var id = data.id
		var list = []
		var multiList = []
		var strs = []
		for(var j = 0;j <= num;j++){
			strs[j] = utils.getBeforeMonth(j,time)
		}
		for(var j = 0;j <= num;j++)
			multiList.push(["hget","editionMonth:"+id,strs[j]])
		redisDao.multi(multiList,function(err,data) {
			var info = []
			for(var j = 0;j <= num;j++){
				if(!data[j])
					data[j] = JSON.stringify({date:strs[j]})
				info.push(data[j])
			}
			res.send(info)
		})
	}
	//获取发行版本
	posts["/getEditions"] = function(req,res) {
		var infos = self.server.edition.getEditions()
		res.send(infos)
	}
	//添加版本
	posts["/addEdition"] = function(req,res) {
		var data = req.body
		console.log("addEdition",data.name)
		self.server.edition.addEdition(data,function(flag,info) {
			res.send({flag:flag,data:info})
		})
	}
	//删除版本
	posts["/delEdition"] = function(req,res) {
		var data = req.body
		var name = data.name
		console.log("delEdition",data.name)
		self.server.edition.delEdition(name,function(flag) {
			res.send({flag,flag})
		})
	}
	//停止更新
	posts["/pauseSync"] = function(req,res) {
		var data = req.body
		var name = data.name
		console.log("pauseSync",data.name)
		self.server.edition.pauseSync(name,function(flag,info) {
			info.flag = flag
			res.send(info)
		})
	}
	//恢复更新
	posts["/resumeSync"] = function(req,res) {
		var data = req.body
		var name = data.name
		console.log("resumeSync",data.name)
		self.server.edition.resumeSync(name,function(flag,info) {
			info.flag = flag
			res.send(info)
		})
	}
	//版本初始化
	posts["/editionInit"] = function(req,res) {
		var data = req.body
		var name = data.name
		var infos = self.server.edition.getEditions()
		var info = infos[name]
		if(info){
			self.server.collection.initEdition(name,info)
			self.server.edition.getDataAndEditionInit(name,function(flag) {
				res.send({flag:flag})
			})
		}else{
			res.send({flag:false})
		}
	}
	//获取底层数据
	posts["/getBasicData"] = function(req,res) {
		var infos = self.server.edition.getBasicData(function(data) {
			res.send(data)
		})
	}
	//添加底层
	posts["/addBasic"] = function(req,res) {
		var data = req.body
		var name = data.name
		var des = data.des
		self.server.edition.addBasic(name,des,function(flag,info) {
			info.flag = flag
			res.send(info)
		})
	}
	//删除底层
	posts["/delBasic"] = function(req,res) {
		var data = req.body
		var name = data.name
		self.server.edition.delBasic(name,function(flag) {
			res.send({flag,flag})
		})
	}
	//获取底层
	posts["/getBasic"] = function(req,res) {
		var infos = self.server.edition.getBasic()
		res.send(infos)
	}
	//获取发行数据
	posts["/getPublishData"] = function(req,res) {
		var infos = self.server.edition.getPublishData(function(data) {
			res.send(data)
		})
	}
	//添加发行
	posts["/addPublish"] = function(req,res) {
		var data = req.body
		var name = data.name
		var des = data.des
		self.server.edition.addPublish(name,des,function(flag,info) {
			info.flag = flag
			res.send(info)
		})
	}
	//删除发行
	posts["/delPublish"] = function(req,res) {
		var data = req.body
		var name = data.name
		self.server.edition.delPublish(name,function(flag) {
			res.send({flag,flag})
		})
	}
	//获取发行
	posts["/getPublish"] = function(req,res) {
		var infos = self.server.edition.getPublish()
		res.send(infos)
	}
	//获取对账单总页数
	posts["/getStatementPage"] = function(req,res) {
		var data = req.body
		self.server.edition.getStatementPage(data,function(flag,info) {
			info = Object.assign({},info)
			info.flag = flag
			res.send(info)
		})
	}
	//获取对账单
	posts["/getStatement"] = function(req,res) {
		var data = req.body
		self.server.edition.getStatement(data,function(flag,info) {
			info = Object.assign({},info)
			info.flag = flag
			res.send(info)
		})
	}
	//添加对账单
	posts["/addStatement"] = function(req,res) {
		var data = req.body
		self.server.edition.addStatement(data,function(flag,info) {
			info = Object.assign({},info)
			info.flag = flag
			res.send(info)
		})
	}
	//对账单回款
	posts["/finishStatement"] = function(req,res) {
		var data = req.body
		self.server.edition.finishStatement(data,function(flag,info) {
			info = Object.assign({},info)
			info.flag = flag
			res.send(info)
		})
	}
	//对账单作废	
	posts["/repealStatement"] = function(req,res) {
		var data = req.body
		self.server.edition.repealStatement(data,function(flag,info) {
			info = Object.assign({},info)
			info.flag = flag
			res.send(info)
		})
	}
	//获取对账单统计数据
	posts["/getStatementStat"] = function(req,res) {
		var data = req.body
		self.server.edition.getStatementStat(data,function(flag,info) {
			info = Object.assign({},info)
			info.flag = flag
			res.send(info)
		})
	}
	//数据校正
	posts["/correctionStatementStat"] = function(req,res) {
		var data = req.body
		mysqlDao.correctionStatementStat(function(flag,info) {
			res.send(info)
		})
	}
	//获取月对账单数据
	posts["/getStatementData"] = function(req,res) {
		var data = req.body
		mysqlDao.getStatementData(data,function(flag,info) {
			res.send(info)
		})
	}
	//获取ChatGPT记录
	posts["/getChatGPT"] = function(req,res) {
		res.send(chatGPT.getMessage())
	}
	//调用ChatGPT接口
	posts["/callChatGPT"] = function(req,res) {
		var data = req.body
		var message = data.message
		chatGPT.callChatGPT(message,function(messageList) {
			res.send(messageList)
		})
	}
	//更新下载数据
	gets["/addLoadCount"] = function(req,res) {
		var data = req.body
		var args = url.parse(req.url, true).query
		var type = args.type
		redisDao.db.hincrby("loadCount",type,1)
		res.send("SUCCESS")
	}
	//获取下载数据
	gets["/getLoadCount"] = function(req,res) {
		var data = req.body
		var args = url.parse(req.url, true).query
		var type = args.type
		redisDao.db.hget("loadCount",type,function(err,data) {
			data = Math.floor(data) || 1
			res.send({value:data})
		})
	}
	//获取下载数据列表
	gets["/getLoadList"] = function(req,res) {
		var data = req.body
		var args = url.parse(req.url, true).query
		redisDao.db.hgetall("loadCount",function(err,data) {
			res.send(data)
		})
	}
	//post请求
	local.post = function(hostname,port,path,args,callback) {
		var postData=querystring.stringify(args)
		var options={
		  hostname:hostname,
		  port:port,
		  path:path,
		  method:'POST',
		  headers:{
		    "Content-Type":"application/x-www-form-urlencoded; charset=utf-8",
		    "Content-Length" : postData.length
		  }
		}
		var req=http.request(options,function(res){
		var _data='';
		res.on('data', function(chunk){
		   _data += chunk;
		});
		res.on('end', function(){
			callback(_data)
		 });
		})
		req.on('error', function(e) {
		  console.error(e)
		})
		req.write(postData);
		req.end()
	}
}
module.exports = new model()